package com.example.bikemanagerjava.controller;

import com.example.bikemanagerjava.common.Result;
import com.example.bikemanagerjava.entity.User;
import com.example.bikemanagerjava.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin("*")
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    //获取用户列表
    @GetMapping("/users")
    public Result selectByPage(@RequestParam Integer page, @RequestParam Integer pageSize,
                               @RequestParam(required = false) Integer status,@RequestParam(required = false) String username){
        Map<String,Object> result=new HashMap<>();
        List<User> user=userService.selectByPage(page,pageSize,status,username);
        int total = userService.countUsers();
        result.put("user",user);
        result.put("total",total);
        return Result.success(result);
    }

    //获取用户详细信息
    @GetMapping("/users/{id}")
    public Result selectById(@PathVariable int id){
        User user = userService.selectById(id);
        return Result.success(user);
    }

    //修改用户信息
    @PutMapping("/users/{id}")
    public Result update(@RequestBody User user,@PathVariable int id){
        user.setUserId(id);
        userService.updateUser(user);
        Map<String, Object> data = new HashMap<>();
        data.put("userId", user.getUserId());
        return Result.success("更新用户信息成功",data);
    }

    //禁用启用用户
    @PutMapping("/users/{id}/status")
    public Result updateStatus(@RequestBody User user, @PathVariable int id) {
        Integer status = user.getStatus();
        if (status == null || (status != 0 && status != 1)) {
            return Result.error(400, null);
        }
        userService.updateUserStatus(id, status);
        Map<String, Object> data = new HashMap<>();
        data.put("userId", id);
        return  Result.success("用户状态更新成功", data);
    }

    //删除用户
    @DeleteMapping("/users/{id}")
    public Result delete(@PathVariable int id){
        userService.deleteUser(id);
        return Result.success("删除成功！");
    }

}
